//
//  SPMapDBInstance.m
//  SPMapKit
//
//  Created by zhangyz on 2017/9/16.
//  Copyright © 2017年 zhangbo. All rights reserved.
//

#import "SPMapDBInstance.h"

@implementation SPMapDBInstance

+ (SPMapDBInstance *) Instance
{
    static SPMapDBInstance* pstObj = nil;
    @synchronized(self)
    {
        if(nil == pstObj)
        {
            pstObj = [[SPMapDBInstance alloc] init];
            NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentDir = [documentPaths objectAtIndex:0];
            pstObj->_dbPath = [documentDir stringByAppendingPathComponent:@"Database/SPMap.db"];
        }
    }
    return pstObj;
}


- (void) createDBAndTable

{
    BOOL isHasTable = NO;
    

    NSLog(@"DB path:%@", _dbPath);
    
    
    
    FMDatabase *db = [self getDB];
    
    if(![db open])
    {
        
        NSLog(@"could not open");
        
    }

    isHasTable = [db executeUpdate:@"create table if not exists mapimage (identifier integer primary key autoincrement , urlstr text, imagedata blob , level integer , row integer , column integer , newtime integer , usecount integer)"];
    
    //组合索引
    [db executeUpdate:@"create index if not exists image_position_index on mapimage (level,row,column)"];

    
    [db close];
    
}

- (FMDatabase*) getDB
{
    return [FMDatabase databaseWithPath:_dbPath];
}

//判断image类型(png、jpeg)
- (BOOL) imageHasAlpha: (UIImage *) image
{
    CGImageAlphaInfo alpha = CGImageGetAlphaInfo(image.CGImage);
    return (alpha == kCGImageAlphaFirst ||
            alpha == kCGImageAlphaLast ||
            alpha == kCGImageAlphaPremultipliedFirst ||
            alpha == kCGImageAlphaPremultipliedLast);
}

- (BOOL) addMapsToDB:(NSMutableDictionary *)dic
{
    
    NSArray *array = [dic allKeys];
    
    BOOL isSuccess = YES;
    
    FMDatabase *db = [self getDB];
    
    if(![db open])
    {
        
        NSLog(@"could not open");
        
    }
    for (int i = 0; i < [array count]; i++)
    {
        MapImageInfo *obj = [dic objectForKey:[array objectAtIndex:i]];
        
        
        NSData *imageData = nil;
        if ([self imageHasAlpha:obj.image])
        {
            imageData = UIImagePNGRepresentation(obj.image);        //png类型图片
        }
        else
        {
            imageData = UIImageJPEGRepresentation(obj.image, 1.0f); //jpeg类型图片
        }
        
        
        BOOL tempSuccess = [db executeUpdate:@"INSERT INTO mapimage(urlstr, imagedata, level, row, column, newtime, usecount) values(?,?,?,?,?,?,?)" , obj.urlStr , imageData, @(obj.level), @(obj.row) , @(obj.column), @(obj.newtime), @(obj.usecount)];
        
      
        
//        NSString *sql = [NSString stringWithFormat:@"insert into mapimage(urlstr, imagedata, level, row, column, newtime, usecount) values(%@, %@ , %ld , %ld , %ld , %ld , %ld )" , obj.urlStr, imageData , obj.level , obj.row , obj.column, obj.newtime, obj.usecount ];
        
//        isSuccess = [db executeUpdateWithFormat:@"insert into mapimage(urlstr, imagedata, level, row, column, newtime, usecount) values(%@, %@ , %ld , %ld , %ld , %ld , %ld )" , obj.urlStr, imageData , obj.level , obj.row , obj.column, obj.newtime, obj.usecount ];
        
        
        NSString *error = [db lastErrorMessage];
        NSLog(@"%@", error);
        
        if (!tempSuccess)
        {
            isSuccess = NO;
        }
    }
    
    [db close];
    
    return isSuccess;
    
}

- (NSMutableDictionary *)getMapsFromDB:(MapImagesPosiionRange *)position
{
    
    FMDatabase *db = [self getDB];
    
    if(![db open])
    {
        
        NSLog(@"could not open");
        
    }
    
    NSMutableDictionary *dic =  [[NSMutableDictionary alloc] init];
    
    //在where子句中，前导列必须使用等于或者in操作，最右边的列可以使用不等式，这样索引才可以完全生效
    FMResultSet *rs=  [db executeQuery:[NSString stringWithFormat:@"select * from mapimage where level>=%ld and level<=%ld and row>=%ld and row<=%ld and column>=%ld and column<=%ld", (long)position.startLevel,(long)position.endLevel, (long)position.startRow, (long)position.endRow, (long)position.startColumn, (long)position.endColumn]];
    
    while ([rs next])
    {
        
        MapImageInfo *sv = [[MapImageInfo alloc]init];
        
        sv.SPid = [rs intForColumn:@"identifier"];
        
        sv.urlStr = [rs stringForColumn:@"urlstr"];
        
        sv.image = [UIImage imageWithData:[rs dataForColumn:@"imagedata"]];
        
        sv.level = [rs intForColumn:@"level"];
        
        sv.row = [rs intForColumn:@"row"];
        
        sv.column = [rs intForColumn:@"column"];
        
        sv.newtime = [rs intForColumn:@"newtime"];
        
        sv.usecount = [rs intForColumn:@"usecount"];
        
        [dic setObject:sv forKey:sv.urlStr];
        
    }
    
    [rs close];
    
    return dic;
    
}

- (MapImageInfo *)getMapFromDB:(MapImagesPosiionRange *)position
{
    
    FMDatabase *db = [self getDB];
    
//    NSLog(@"dbPath is:%@" ,dbPath);
    
    if(![db open])
    {
        NSLog(@"could not open");
    }
    
    
    FMResultSet *rs=  [db executeQuery:[NSString stringWithFormat:@"select * from mapimage where level='%ld' and row='%ld' and column='%ld'", (long)position.startLevel, (long)position.startRow, (long)position.startColumn]];
    
    MapImageInfo *sv = nil;
    
     while ([rs next])
     {
        sv = [[MapImageInfo alloc]init];
         
        sv.SPid = [rs intForColumn:@"identifier"];
        
        sv.urlStr = [rs stringForColumn:@"urlstr"];
         
        NSData *tempData = [rs dataForColumn:@"imagedata"];
        UIImage *tempImage = [UIImage imageWithData:tempData];
        sv.image = tempImage;
         
        sv.level = [rs intForColumn:@"level"];
        
        sv.row = [rs intForColumn:@"row"];
        
        sv.column = [rs intForColumn:@"column"];
        
        sv.newtime = [rs intForColumn:@"newtime"];
        
        sv.usecount = [rs intForColumn:@"usecount"];
         
    }
    
    
    [rs close];

    return sv;
    
}

@end
